<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2017/9/5
 * Time: 下午5:41
 */

namespace Mq\model;

use MongoDB\Client;

class ClientBaseModel
{
    public static $_instance = null;

    public $client;

    public $dbName = 'test';

    public $tableName = '';

    public $collection = '';

    /**
     *  初始化方法
     * ClientBaseModel constructor.
     */
    public function __construct()
    {
        $this->client = new Client('mongodb://admin:123456@localhost/test?authSource=admin');
//        $this->client = new Client('mongodb://localhost/test');
        $this->getCollection();
    }

    /**
     *  获取相应实例
     * @return null|static
     */
    public static function getInstance()
    {
        if (!isset(self::$_instance) && !(self::$_instance instanceof static)) {
            self::$_instance = new static;
        }
        return self::$_instance;
    }

    /**
     *  获取表格实例
     */
    public function getCollection()
    {
        $dbName = $this->dbName;
        $tableName = $this->tableName;
        $this->collection = $this->client->$dbName->$tableName;

    }

    /**
     * 插入新的数据
     * @param $data
     * @return bool|mixed
     */
    public function insert($data)
    {

        $result = $this->collection->insertOne($data);

        if (empty($result->getInsertedCount())) {
            return false;
        }
        return $result->getInsertedId();
    }

    /**
     * 获取实例
     * @param $data
     * @return mixed
     */
    public function getInfo($data)
    {
        return $this->collection->find($data);
    }
}